﻿public class Solution560
{
    public int SubarraySum1(int[] nums, int k)
    {


        int preIndex = 0;
        int curIndex = 0;
        int sum = 0;
        int arrayNum = 0;//数组的数量
        bool isAdd = false;
        //for (int i = 0;i<nums.Length;i++) { 

        while (preIndex < nums.Length)
        {

            if (curIndex == nums.Length)
            {
                curIndex = nums.Length - 1;
            }

            if (sum < k)
            {

                sum += nums[curIndex];
                curIndex++;


            }
            else if (sum > k)
            {
                sum -= nums[preIndex];
                preIndex++;


            }
            else
            {
                if (isAdd)
                {


                    sum += nums[curIndex];
                    curIndex++;
                    isAdd = false;
                }
                else
                {
                    arrayNum++;
                    isAdd = true;
                }




            }
        }
        return arrayNum++;
    }
    //使用两个循环
    public int SubarraySum(int[] nums, int k)
    {
        //int preIndex = 0;

        int sum = 0;
        int arrayNum = 0;//数组的数量


        for (int preIndex = 0; preIndex < nums.Length; preIndex++)
        {
            sum = 0;

            for (int curIndex = preIndex; curIndex < nums.Length; curIndex++)
            {



                //if (sum < k)
                //{
                //    sum += nums[curIndex];
                //}
                //else if (sum > k)
                //{
                //    break;//超过了不要停止，前面可能有负数
                //}
                //else
                //{
                //    arrayNum++;
                //}

                sum += nums[curIndex];
                if (sum == k)
                {
                    arrayNum++;
                }

            }

        }

        return arrayNum++;
    }
}

class Program560
{

    static void Main560(string[] args)
    {
        Solution560 solution = new();
        int[] nums = { 1, 1, 1 }; // 你可以根据需要修改 nums 的值
        int k = 2; // 你可以根据需要修改 k 的值

        int count = solution.SubarraySum(nums, k);
        Console.WriteLine("Number of subarrays with sum " + k + ": " + count);

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }


}


